/**
 * 功能权限树store
 */
if (Ext.data.StoreManager.lookup('permTreeStore') == null) {
    Ext.create('Ext.data.TreeStore', {
        storeId: 'permTreeStore',
        proxy: {
            type: 'ajax',
            url: F.url('/admin/role/perm_treenodes.do')
        },
        autoLoad: false
    });
}

//角色管理
Ext.define('manager.role', {
    extend: 'Ext.Panel',
    layout: 'border',
    initComponent: function () {
        var _this = this;
        var grid;
        var keywordsField = Ext.create('Ext.form.field.Text', {
            // 这里打算使用 hibernate serach 几个列加全文搜索，不针对具体字段搜索
            name: 'keywords',
            xtype: 'textfield'
        });
        // 工具栏
        this.tbar = [
            {
                text: '添加',
                icon: F.url("/resources/icons/16/add.png"),
                handler: function () {
                    _this.showAddWindow();
                }
            },
            {
                text: '编辑',
                icon: F.url("/resources/icons/16/application_edit.png"),
                handler: function () {
                    if (grid.getSelectionModel().hasSelection()) {
                        var record = grid.getStore().getById(grid.getSelectionModel().getSelection()[0].getId());
                        _this.showEditWindow(record);
                    }
                }
            },
            {
                text: '删除',
                icon: F.url("/resources/icons/16/delete.png"),
                handler: function () {
                    if (grid.getSelectionModel().hasSelection()) {
                        var record = grid.getStore().getById(grid.getSelectionModel().getSelection()[0].getId());
                        Ext.Msg.confirm('严重', "！！！删除角色将会使所有具有此角色的用户失去部分权利，是否继续？", function (b) {
                            if (b != 'yes') {
                                return;
                            }
                            Ext.Ajax.request({
                                url: F.url("/admin/role/remove.do"),
                                params: {
                                    roleId: record.get('roleId')
                                },
                                success: function (response) {
                                    var text = response.responseText;
                                    var result = Ext.JSON.decode(text);
                                    if (result.success) {
                                        grid.getStore().reload();
                                    } else {
                                        UI.showErrorMsg("删除失败", result.error || "请重试");
                                    }
                                },
                                failure: function (response, opts) {
                                    UI.showErrorMsg("删除失败", "内部错误");
                                }
                            });
                        });
                    }
                }
            }
        ];
        var columns = [
            {
                xtype: 'rownumberer'
            },
//            {
//                text: '主键',
//                dataIndex: 'roleId'
//            },
            {
                text: '名称',
                dataIndex: 'roleName',
                flex: 1
            },
            {
                text: '说明',
                dataIndex: 'description',
                flex: 2
            }
        ];
        var fields = [ 'roleId', 'roleName', {
            name: 'description',
            type: 'string'
        } ];
        var store = Ext.create('Ext.data.Store', {
            storeId: 'roleStore',
            pageSize: 50,
            proxy: {
                type: 'ajax',
                url: F.url('/admin/role/list.do'),
                method: 'post',
                extraParams: {},
                reader: {
                    type: 'json',
                    root: 'pageList.list',
                    idProperty: 'roleId',
                    totalProperty: 'pageList.page.total',
                    messageProperty: "msg"
                }
            },
            fields: fields
        });
        // 列表
        grid = Ext.create('Ext.grid.Panel', {
            itemId: 'grid',
            dockedItems: [
                {
                    xtype: 'pagingtoolbar',
                    store: store, // same store GridPanel is using
                    dock: 'bottom',
                    displayInfo: true
                }
            ],
            region: 'center',
            store: store,
            columns: columns,
            listeners: {
                render: function () {
                    store.load();
                },
                itemdblclick: function (g, record, item, index, e, eOpts) {
                    _this.showEditWindow(record);
                }
            }
        });
        _this.items = [ grid ];
        this.callParent();
    },
    // 弹出添加窗口
    showAddWindow: function () {
        var _this = this;
        var win = Ext.create('manager.role.FormWindow', {
            title: '创建角色',
            formUrl: F.url('/admin/role/add.do'),
            submitSuccessCallback: function (win) {
                win.close();
                UI.showSuccessMsg("添加角色成功");
                _this.getComponent('grid').getStore().reload();
            }
        });

        win.show();
    },
    // 弹出修改窗口
    showEditWindow: function (rec) {
        var _this = this;
        var win = Ext.create('manager.role.FormWindow', {
            title: '编辑角色和权限',
            formUrl: F.url('/admin/role/update.do'),
            submitSuccessCallback: function (win) {
                win.close();
                UI.showSuccessMsg("修改角色成功");
                _this.getComponent('grid').getStore().reload();
            }
        });
        win.show();
        win.loadRecord(rec);
    }
});
// 角色Form表单窗口
Ext.define('manager.role.FormWindow', {
    extend: 'Ext.window.Window',
    height: 600,
    width: 900,
    layout: 'border',
    modal: true,
    initComponent: function () {
        var win = this;
        var form = Ext.create("Ext.form.Panel", {
            itemId: 'form',
            region: 'center',
            bodyPadding: 5,
            url: this.formUrl,
            layout: 'anchor',
            defaults: {
                anchor: '100%'
            },
            // The fields
            defaultType: 'textfield',
            items: [
                {
                    xtype: 'hiddenfield',
                    name: 'roleId'
                },
                {
                    fieldLabel: '角色名称',
                    name: 'roleName',
                    allowBlank: false,
                    emptyText: '请输入角色名称',
                    blankText: '角色名称不能为空'
                },
                {
                    fieldLabel: '说明',
                    name: 'description',
                    allowBlank: true,
                    xtype: 'textareafield'
                }
            ]
        });

        var tree = Ext.create('Admin.common.CheckableTreePanel', {
            title: '权限',
            header: false,
            region: 'west',
            width: 500,
            height: 150,
            itemId: 'permTree',
//            rootVisible: true,
            columns: [
                {
                    xtype: 'treecolumn', //this is so we know which column will show the tree
                    text: '权限',
                    flex: 2,
                    sortable: false,
                    dataIndex: 'text',
                    menuDisabled: true

                },
                {
                    text: '修改后状态',
                    dataIndex: 'checked',
                    sortable: false,
                    menuDisabled: true,
                    renderer: function (v, m, r) {
                        if (r.raw.type == 'module') {
                            return '';
                        }
                        if (v === true) {
                            m.tdCls = 'bg green';
                            return '有权';
                        } else {
                            m.tdCls = 'bg red';
                            return '无权';
                        }
                        return v;
                    }
                },
                {
                    text: '修改前状态',
                    flex: 1,

                    menuDisabled: true,
                    renderer: function (v, m, r) {
                        if (r.raw.type == 'module') {
                            return '';
                        }
                        if (r.raw.alreadyChecked) {
                            m.tdCls = 'bg green';
                            return '有权';

                        } else {
                            m.tdCls = 'bg red';
                            return '无权';
                        }
                    }
                }
            ],
            store: Ext.data.StoreManager.lookup('permTreeStore'),
//            tools: [
//                {
//                    type: 'refresh',
//                    callback: function (tree, tool, event) {
//                        Ext.data.StoreManager.lookup('permTreeStore').load();
//                    }
//                }
//            ],
            root: {
                expanded: true,
                text: "ROOT"
            }
        });
        Ext.apply(this, {
            buttons: [
                {
                    text: '取消',
                    scope: this,
                    handler: function () {
                        Ext.Msg.confirm('确定取消', "您确定取消并关闭窗口吗？", function (b) {
                            if (b != 'yes') {
                                return;
                            }
                            win.close();
                        });
                    }
                },
                {
                    text: '确认',
                    scope: this,
                    handler: function () {
                        // 收集角色,与表单一起提交
                        var records = win.getComponent('permTree').getChecked();
                        var perms = [];
                        Ext.Array.each(records, function (rec) {
                            if (rec.raw.id) {
                                perms.push(rec.raw.id);
                            }
                        });
                        win.getComponent('form').submit({
                            clientValidation: true,
                            params: {
                                perms: perms
                            },
                            success: function (form, action) {
                                if (win.submitSuccessCallback) {
                                    win.submitSuccessCallback(win);
                                } else {
                                    win.close();
                                }
                            },
                            failure: function (form, action) {
                                if (win.submitFailureCallback) {
                                    win.submitFailureCallback(win);
                                } else {
                                    switch (action.failureType) {
                                        case Ext.form.action.Action.CLIENT_INVALID:
                                            UI.showErrorMsg('失败', '请检查输入的内容是否完整并且无误');
                                            break;
                                        case Ext.form.action.Action.CONNECT_FAILURE:
                                            UI.showErrorMsg('失败', '请求超时，请检查网络是否正常');
                                            break;
                                        case Ext.form.action.Action.SERVER_INVALID:
                                            UI.showErrorMsg('失败', action.result.error);
                                    }
                                }
                            }
                        });
                    }
                }
            ]
        });
        this.items = [ tree, form ];
        this.callParent();
    },
    loadRecord: function (role) {
        var tree = this.getComponent('permTree');
        this.getComponent('form').loadRecord(role);
        tree.getStore().reload({
            callback: function (records, operation, success) {
                Ext.Ajax.request({
                    url: F.url('/admin/role/perms.do'),
                    params: {
                        roleId: role.get("roleId")
                    },
                    success: function (response) {
                        tree.setLoading(false);
                        var obj = Ext.decode(response.responseText);
                        if (obj.success) {
                            tree.allUncheck()
                            for (var i = 0; i < obj.perms.length; i++) {
                                var p = obj.perms[i];
                                var r = tree.getStore().getById(p);
                                if (r) {
                                    r.set('checked', true);
                                    r.raw.alreadyChecked = true;
                                }
                            }
                            tree.getView().refresh();
                        } else {

                        }
                    }
                });
            }
        });

    }
});